package com.rampage.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by chenzipeng on 2017/7/4.
 */
public class NetUtils {
    /**
     * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
     *
     * @param request
     * @return ip
     */
    public static String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                //ip = remoteAddr + "/" + forwarded.split(",")[0];
                ip = forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if (forwarded != null) {
                    //ip = realIp + "/" + forwarded.split(",")[0];
                    ip = forwarded.split(",")[0];
                } else {
                    ip = realIp;
                }

            }
        }
        return ip;
    }
}
